package com.example.springbootweb_comprehensiveexample.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.springbootweb_comprehensiveexample.pojo.Result;
import com.example.springbootweb_comprehensiveexample.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //1.获取请求url
        String url = req.getRequestURI().toString();
        log.info("请求的url：{}", url);

        //2.判断请求url中是否含有/login
        if(url.contains("login")){
            log.info("为登录操作，放行");
            chain.doFilter(request, response);
            return ;
        }

        //3.获取请求头中的令牌（Token）
        String jwt = req.getHeader("token");

        //4.判断令牌是否存在
        if(!StringUtils.hasLength(jwt)){
            log.info("token为空，未登录，返回至登录页面");
            Result error = Result.error("NOT_LOGIN");
            //手动转换为json格式响应回去------>阿里fastJSON工具包
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return;
        }

        //5.校验令牌是否正确
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {//jwt校验失败
            e.printStackTrace();
            log.info("校验令牌失败，返回登录页");
            Result error = Result.error("NOT_LOGIN");
            //手动转换为JSON格式------>阿里fastjson工具包
            String notLogin = JSONObject.toJSONString(error);
            resp.getWriter().write(notLogin);
            return ;
        }

        //6.放行
        log.info("校验成功");
        chain.doFilter(request, response);
    }
}
